#! /usr/bin/env python
# This script replaces header guards in all header files in current directory and
# subdirectories with the format: __INET_[FILENAME]_H.
#

import re
import string
import fnmatch
import os

# configuration parameters
rootPath = '.'
fileType = '*.h'

def getUpperCaseFilename(filename) :
    return filename[:-2].upper()

err = 0
symbolmap = dict()
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, fileType):
        symbol = "__INET_" + re.sub("[^A-Z0-9]", "_", getUpperCaseFilename(filename)) + "_H"
        fullpath = os.path.join(root, filename)
        if symbol in symbolmap:
            print("ERROR: duplicate filename detected: ", filename, ": ", fullpath, " vs ", symbolmap[symbol])
        else:
            symbolmap[symbol] = fullpath
            f = open(fullpath, 'r')
            headerFile = f.read()
            pattern = "#ifndef .*_H.*\n#define.*"
            m = re.search(pattern, headerFile)
            if not m:
                print("ERROR: ", filename, " doesn't have any headerguard")
            else:
                replacement = "#ifndef " + symbol + "\n#define " + symbol
                newHeader = headerFile
                newHeader = re.sub(pattern, replacement, newHeader)
                pattern = "#endif.*?\n\s*\Z"
                replacement = "#endif\n\n"
                newHeader = re.sub(pattern, replacement, newHeader)
                if headerFile != newHeader:
                    f2 = open(fullpath, 'w')
                    f2.write(newHeader)
                    f2.close()
            f.close()
